package com.pearl.authorize.hierarchy.demo;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity(debug = true)
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class PearlWebSecurityConfig {

    /**
     * 使用`RoleHierarchyImpl`定义角色层级关系，并设置到基于方法的表达式处理器中：
     */
    @Bean
    protected MethodSecurityExpressionHandler methodSecurityExpressionHandler() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); // 角色层级关系，多个使用`\n`分割
        roleHierarchy.setHierarchy("ROLE_admin > ROLE_leader\n" +
                "ROLE_leader > ROLE_staff > ROLE_anonymous");
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setRoleHierarchy(roleHierarchy);
        return expressionHandler;
    }

    /**
     * 基于内存创建用户
     */
    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager detailsManager = new InMemoryUserDetailsManager();
        // 部门负责人
        detailsManager.createUser(User.withUsername("group_leader").password("{noop}123456").roles("leader").build());
        // 普通员工
        detailsManager.createUser(User.withUsername("general_staff").password("{noop}123456").roles("staff").authorities("save").build());
        return detailsManager;
    }

    /**
     *
     *
     */
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        // authorizeHttpRequests：指定多个授权规则，按照顺序
        http.authorizeHttpRequests(request -> {
            request.anyRequest().authenticated();
        });
        // 开启表单登录
        http.formLogin(formLogin -> {
        });
        return http.build();
    }

}